package com.attendance.service;



import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.attendance.dao.LeaveRepository;
import com.attendance.entity.Leave;
import com.attendance.entity.dto.LeaveDTO;
import com.staff.entity.Staff;

@Service
@Transactional
public class LeaveService implements ILeaveService {
	@Autowired
	private LeaveRepository leaveDao;

	public Page<LeaveDTO> findPage(String staffName, String staffNum, Pageable pageable) {
		List<LeaveDTO> results = new ArrayList<LeaveDTO>();
		List<Leave> list = new ArrayList<Leave>();
		if(staffName!=""&&staffName!=null) {
			list = leaveDao.findLikeStaffName(staffName);
		}else if(staffNum!=""&&staffNum!=null) {
			list = leaveDao.findLikeStaffNum(staffNum);
		}else {
			list = (List<Leave>) leaveDao.findAll();
		}
		for(Leave a:list) {
			Staff staff = a.getStaff();
			Staff operator = a.getAuditor();
			String auditor = null;
			if(operator!=null)auditor = operator.getStaffName();
			if(staff == null)return null;
			String dept = null;
			if(staff!=null) {
				if(staff.getDepartment()!=null)dept = staff.getDepartment().getName();
			}
			results.add(new LeaveDTO(staff,a,dept,auditor));
		}
		List<LeaveDTO> page = new ArrayList<LeaveDTO>();
		int i = pageable.getPageNumber()*pageable.getPageSize();
		int n = i+pageable.getPageSize();
		while(i<results.size()&&i<n) {
			page.add(results.get(i));
			i++;
		}
		return new PageImpl<LeaveDTO>(page,pageable,page.size());
	}

}
